<template>
  <base-breadcrumb :title="title">
    <!-- 质量责任书详情 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="loading">
        <!-- 基础信息 -->
        <a-card :bordered="false" style="margin-bottom: 50px">
          <custom-form :formList="formList" :form="form" :editModel="editModel == 0 ? 'V' : ''"></custom-form>
          <a-button v-if="editModel != 0" class="mb12" icon="plus" @click="handleAddRow" type="primary"
            >添加责任书内容</a-button
          >
          <a-table class="mb20" :dataSource="form.contents" :columns="columns" :pagination="false">
            <!-- 责任书标题 -->
            <template slot="titles" slot-scope="text, record">
              <div v-if="editModel == 0">{{ record.title }}</div>
              <BaseInput v-else v-model="record.title" placeholder="请输入责任书标题" />
            </template>
            <!-- 责任书内容 -->
            <template slot="details" slot-scope="text, record">
              <template v-if="editModel == 0">
                <div v-for="(item, index) in record.details" :key="index">
                  {{ item.content }}
                  <!-- {{ item.serialNumber }}、{{ item.content }} -->
                </div>
              </template>
              <BaseTextarea
                v-else
                :maxLength="3000"
                v-for="(item, index) in record.details"
                :key="index"
                v-model="item.content"
                placeholder="请输入责任书内容"
                :style="{ marginTop: index == 0 ? 0 : '20px' }"
              />
            </template>
            <!-- 操作栏 -->
            <template slot="actions" slot-scope="text, record, index">
              <div
                v-for="(item, idx) in record.details"
                :key="idx"
                :style="{ marginTop: idx == 0 ? 0 : '20px', lineHeight: '73px' }"
              >
                <a v-if="idx == record.details.length - 1" @click="handleAddDetail(record.details)">添加</a>
                <a-divider v-if="idx == record.details.length - 1" type="vertical"></a-divider>
                <a class="del_btn" @click="handleDelete(record.details, idx, index)">删除</a>
              </div>
            </template>
          </a-table>
          <div class="btn_box">
            <a-button type="primary" :disabled="!form.contents || !form.contents.length" :loading="preLoading" @click="handlePreViewWord">预览</a-button>
          </div>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="tool-btns--fixed btn_box page-btn-right-top">
        <a-button :loading="loading" v-if="editModel != 0" type="primary" class="button_right" @click="handleSubmit"
          >提交</a-button
        >
        <a-button type="primary" @click="$multiTab.close()">关闭</a-button>
      </div>
    </a-form-model>
    <!-- 责任书预览 -->
    <DutyPreView ref="dutyPreView" :id="id" />
  </base-breadcrumb>
</template>

<script>
import { postDutyBook } from '@/api/quality/quality' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import Selector from '@/components/Select/Selector' // 分包商
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import DutyPreView from '../dutySystem/components/DutyPreView' // 责任书预览

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    DutyPreView
  },
  data() {
    return {
      loading: false, // 加载loading
      editModel: 0, // 0 查看；1 编辑；2 新增
      form: {
        filler: void 0,
        fillerDate: void 0,
        contents: []
      },
      id: '',
      isPreview: false,
      rules: {
        name: [{ required: true, whitespace: true, message: '请输入责任书名称', trigger: 'change' }],
        postId: [{ required: true, message: '请选择岗位名称', trigger: 'change' }],
        bookTypeId: [{ required: true, message: '请选择岗位类型', trigger: 'change' }],
        branchComId: [{ required: true, message: '请选择分公司', trigger: 'change' }]
      }, // 表单校验规则
      preLoading: false,
      titles: ['查看质量责任书', '编辑质量责任书', '新增质量责任书'] // 标题
    }
  },
  mounted() {
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading = true
      postDutyBook
        .getDetail({ id: this.id })
        .then((res) => {
          this.loading = false
          if (res.code === 200) {
            res.data.reviewFileArrays = res.data.reviewFileArrays || []
            res.data.prizeFileArrays = res.data.prizeFileArrays || []
            this.form = res.data
          }
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      this.form.filler = this.$userInfo()?.name // 默认填报人
      this.form.fillerDate = this.$dateFormat(new Date(), 'D') // 默认填报时间
    }
  },
  computed: {
    // 表头
    columns() {
      return [
        {
          dataIndex: 'title',
          title: '责任书标题',
          width: 300,
          scopedSlots: { customRender: 'titles' }
        },
        {
          dataIndex: 'details',
          title: '责任书内容',
          scopedSlots: { customRender: 'details' }
        },
        this.editModel != 0 && {
          title: '操作',
          dataIndex: 'actions',
          width: '150px',
          align: 'center',
          scopedSlots: { customRender: 'actions' }
        }
      ]
    },
    // 表单配置项
    formList() {
      return [
        {
          title: '基础信息'
        },
        {
          type: SelectSubCompany,
          keyName: 'branchComId',
          label: '所属单位',
          viewName: 'branchComName',
          attrs: {
            autoSelected: this.editModel == 2
          }
        },
        {
          keyName: 'filler',
          type: 'a-input',
          disabled: true,
          label: '创建人'
        },
        {
          keyName: 'fillerDate',
          type: 'a-input',
          disabled: true,
          label: '创建时间'
        },
        {
          title: '质量责任书信息'
        },
        {
          keyName: 'name',
          type: 'BaseInput',
          label: '责任书名称'
        },
        {
          type: Selector,
          keyName: 'postId',
          viewName: 'postName',
          label: '岗位名称',
          attrs: {
            selectType: '53'
          }
        },
        {
          type: Selector,
          keyName: 'bookTypeId',
          viewName: 'bookTypeName',
          label: '岗位类型',
          attrs: {
            selectType: '54'
          }
        }
      ]
    }
  },
  methods: {
    /**
     * 预览责任书
     */
    async handlePreViewWord() {
      if (this.editModel != 0) {
        // 校验责任书
        if (!this.form.contents?.length) {
          this.$message.warning('责任书列表内容不能为空！')
          return
        }
        let form = this.$clone(this.form)
        form.statusCode = 0
        if (this.editModel == 3) {
          form.id = this.id
        }
        if (this.editModel == 1) {
          delete form.id
        }
        this.preLoading = true
        let name = form.id ? 'updatePost' : 'create' // 根据操作切换url地址
        const res = await postDutyBook[name](form).catch(() => {
          this.preLoading = false
        })
        this.preLoading = false
        if (res.code == 200) {
          this.id = res.data.id
          if (this.editModel == 2) {
            this.form.id = res.data.id
          }
          this.editModel = 3
        } else {
          return
        }
      }
      this.$nextTick(() => {
        // 标识已预览
        this.isPreview = true
        this.$refs.dutyPreView?.handlePreViewWord()
      })
    },
    /**
     * 添加行
     */
    handleAddRow() {
      this.$set(this.form.contents, this.form.contents?.length || 0, {
        key: 'a' + Date.now(),
        title: void 0,
        details: [
          {
            serialNumber: 1,
            content: void 0
          }
        ]
      })
    },
    /**
     * 添加当前行责任书内容
     * @param {Array} list -当前行责任书内容
     */
    handleAddDetail(list) {
      this.$set(list, list.length, {
        serialNumber: list.length ? list.length + 1 : 1
      })
    },
    /**
     * 删除行
     * @param {Array} list -当前行责任书内容列表
     * @param {Number} idx -当前行责任书内容索引值
     * @param {Number} index -当前行索引值
     */
    handleDelete(list, idx, index) {
      // 如果是当前行最后一条责任书内容，则删除整行，否则只删除当前行责任书内容
      if (list.length === 1) {
        // 删除当前行
        this.form.contents.splice(index, 1)
      } else {
        // 删除当前行责任书内容
        list.splice(idx, 1)
        // 重新排序
        list.forEach((item, i) => {
          item.serialNumber = i + 1
        })
      }
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      let that = this
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          // 校验责任书
          if (that.form.contents?.length) {
            for (let index in that.form.contents) {
              let item = that.form.contents[index]
              // 校验责任书标题
              if (!item.title) {
                this.$message.warning(`第${Number(index) + 1}行责任书标题不能为空！`)
                return
              }
              // 校验责任书内容
              for (let idx in item.details) {
                let row = item.details[idx]
                if (!row.content) {
                  this.$message.warning(`第${Number(index) + 1}行责任书的第${Number(idx) + 1}行责任书内容不能为空！`)
                  return
                }
              }
            }
          } else {
            this.$message.warning('责任书列表内容不能为空！')
            return
          }
          // 校验是否预览
          if (!this.isPreview) {
            this.$message.warning('请先预览责任书信息！')
            return
          }
          let name = that.id ? 'updatePost' : 'create' // 根据操作切换url地址
          that.$confirm({
            title: '温馨提示',
            content: '确定提交，提交后不可撤回？',
            onOk: () => {
              let form = that.$clone(that.form)
              form.statusCode = 1
              return postDutyBook[name](form).then((res) => {
                if (res.code === 200 || res.data.code === 200) {
                  that.$message.success('提交成功！')
                  that.$multiTab.close()
                }
              })
            }
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-calendar-picker {
  width: 100% !important;
}
</style>
